package utils;

import helper.GlobalConfig;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import models.admin.AdminUser;
import models.admin.enums.AdminUserType;
import models.bill.Bill;
import models.campus.Campus;
import models.contract.ContractCardRelation;
import models.contract.ContractRoom;
import models.issue.Issue;
import models.user.User;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.Play;
import util.common.ConvertUtil;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created by LiuBin on 2017/2/24.
 */
public class WxMsgTempUtil {
    private static WxMpConfigStorage wxMpConfigStorage = null;

    /**
     * 通过CorpApp得到微信配置.
     */
    public static WxMpConfigStorage getWxMpConfigStorage() {
        if (wxMpConfigStorage == null) {
            wxMpConfigStorage = initWxMpConfigStorage();
        }
        return wxMpConfigStorage;
    }
    private static WxMpConfigStorage initWxMpConfigStorage() {
        WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
        wxMpConfigStorage.setAppId(GlobalConfig.WEIXIN_APP_ID);     // 设置微信公众号的appid
        wxMpConfigStorage.setSecret(GlobalConfig.WEIXIN_APP_SECURET);    // 设置微信公众号的app corpSecret
        wxMpConfigStorage.setToken(GlobalConfig.WEIXIN_TOKEN);       // 设置微信公众号的token
        wxMpConfigStorage.setAesKey(GlobalConfig.WEIXIN_AES_KEY);      // 设置微信公众号的EncodingAESKey
        return wxMpConfigStorage;
    }
    /**
     * 通过ConfigStore得到微信服务接口.
     */
    public static WxMpService getWxMpService(WxMpConfigStorage wxMpConfigStorage) {
        WxMpServiceImpl wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpConfigStorage);
        return wxMpService;
    }

    /**
     * 报修派工给维修人员提醒(停止使用)
     * @param issueId
     * @return
     */
    public static Boolean distributeWork(String issueId) {
        Boolean bol = false;
        if (StringUtils.isNotBlank(issueId)) {
            Issue issue = new Issue();
            issue = Issue.findByIdAndUnDeleted(issueId);
            if(issue.serviceUser==null || issue.serviceUser.weiXinUser == null)
                return bol;
            String openId = issue.serviceUser.weiXinUser.openId;
            if(StringUtils.isBlank(openId)) {
                bol = false;
                return bol;
            }
            System.out.println("distributeWork,Work In"+openId);
            WxMpService wxMpService = getWxMpService(getWxMpConfigStorage());
            WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
            wxMpTemplateMessage.setToUser(openId);
            wxMpTemplateMessage.setTemplateId("5d1-DgsuM-c3qKr_txBbipBAeveCbscfxfXjlTdzf2Q");
            String weixinUrl = Play.configuration.getProperty("weixin.url");
            weixinUrl  = weixinUrl+ "issue/issueDetail/"+issueId;
            wxMpTemplateMessage.setUrl(weixinUrl);
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("detail",issue.issueName));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("begindate", DateUtil.dateToString(issue.visitTimeBegin,"yyyy-MM-dd HH:mm:ss")));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("enddate",DateUtil.dateToString(issue.visitTimeEnd,"yyyy-MM-dd HH:mm:ss")));
            try {
                wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
                bol = true;
            } catch (WxErrorException e) {
                Logger.info("weixinCode : %s 发送模板消息失败 . 错误原因 : %s", openId, e.getMessage());
            }
        }
        return bol;
    }

    /**
     * 报修受理推送给客户消息推送
     * @param issueId
     * @return
     */
    public static Boolean repairAcceptForCustomMsg(String issueId,String operator) {
        Boolean bol = false;
        if (StringUtils.isNotBlank(issueId)) {
            Issue issue = new Issue();
            issue = Issue.findByIdAndUnDeleted(issueId);//报修详情
            AdminUser adminUser = AdminUser.findById(ConvertUtil.toLong(operator));//服务人员
            if(adminUser==null )
                return bol;
            String openId = issue.user.openId;
            if(StringUtils.isBlank(openId)) {
                bol = false;
                return bol;
            }
            System.out.println("repairAcceptForCustomMsg,Work In"+openId);
            WxMpService wxMpService = getWxMpService(getWxMpConfigStorage());
            WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
            wxMpTemplateMessage.setToUser(openId);
            wxMpTemplateMessage.setTemplateId("Q4i_69e9KEI649LeyTPn2AxE8f3vCsL327DRdnjmI-Y");
            String weixinUrl = Play.configuration.getProperty("weixin.url");
            weixinUrl  = weixinUrl+ "issue/issueDetail/"+issueId;
            wxMpTemplateMessage.setUrl(weixinUrl);
//            wxMpTemplateMessage.setUrl("http://wuyeweixin.ulmsale.cn");
         /*   wxMpTemplateMessage.getData().add(new WxMpTemplateData("detail",issue.issueName));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("begindate", DateUtil.dateToString(issue.visitTimeBegin,"yyyy-MM-dd HH:mm:ss")));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("enddate",DateUtil.dateToString(issue.visitTimeEnd,"yyyy-MM-dd HH:mm:ss")));*/

            wxMpTemplateMessage.getData().add(new WxMpTemplateData("first", "您好！我们已经为您为安排了维修小哥，请耐心等待！" ));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword1",DateUtil.dateToString(issue.visitTimeBegin!=null ? issue.visitTimeBegin:new Date(),"yyyy-MM-dd HH:mm"+"到"+DateUtil.dateToString(issue.visitTimeEnd!=null?issue.visitTimeEnd:new Date(),"yyyy-MM-dd HH:mm"))));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword2",adminUser.name!=null ? adminUser.name:""));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword3", adminUser.phoneNo!=null ? adminUser.phoneNo:"" ));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("remark", "感谢您的合作，如有疑问请及时联系我们。"));
            try {
                wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
                bol = true;
            } catch (WxErrorException e) {
                Logger.info("weixinCode : %s 发送模板消息失败 . 错误原因 : %s", openId, e.getMessage());
            }
        }
        return bol;
    }

    /**
     * 发送每月账单生成信息给财务（停止使用）
     * @param billNums
     * @return
     */
    public static Boolean sendBillMsgToFinance(Long billNums) {
        Boolean bol = false;
        if (billNums != null && billNums> 0) {
            AdminUser adminUser =  AdminUser.findAdminUserByType(AdminUserType.FINANCE);
            if(adminUser != null && adminUser.weiXinUser != null) {
                String openId = adminUser.weiXinUser.openId;
                if(StringUtils.isBlank(openId)) {
                    bol = false;
                    return bol;
                }
                System.out.println("sendBillMsgToFinance,Work In"+openId);
                String currentMonth = DateUtil.dateToString(DateUtil.lastMonthOfFirstDay(new Date()),"yyyy年MM月");
                WxMpService wxMpService = getWxMpService(getWxMpConfigStorage());
                WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
                wxMpTemplateMessage.setToUser(openId);
                wxMpTemplateMessage.setTemplateId("j55i5-uMwbS3bsSHdWvFUXH6_QgaUk8G1Pnk8zRkHlw");
                String weixinUrl = Play.configuration.getProperty("weixin.url");
//            weixinUrl  = weixinUrl+ "issue/issueDetail/"+issueId;
                wxMpTemplateMessage.setUrl(weixinUrl);
                wxMpTemplateMessage.getData().add(new WxMpTemplateData("date",currentMonth));
                wxMpTemplateMessage.getData().add(new WxMpTemplateData("billNums",billNums.toString()));
                try {
                    wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
                    bol = true;
                } catch (WxErrorException e) {
                    Logger.info("weixinCode : %s 发送模板消息失败 . 错误原因 : %s", openId, e.getMessage());
                }
            }
        }
        return bol;
    }

    /**
     * 发送每月账单详情给客户推送
     * @param bill
     * @return
     */
    public static Boolean sendBillDetailToCustom(Bill bill) {
        Boolean bol = false;
        if (bill != null && bill.user != null) {
            String openId = bill.user.openId;
            if(StringUtils.isBlank(openId)) {
                bol = false;
                return bol;
            }
            System.out.println("sendBillDetailToCustom,Work In"+openId);
            String currentMonth = DateUtil.dateToString(DateUtil.lastMonthOfFirstDay(new Date()),"yyyy年MM月");
            WxMpService wxMpService = getWxMpService(getWxMpConfigStorage());
            WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
            wxMpTemplateMessage.setToUser(openId);
            wxMpTemplateMessage.setTemplateId("4z1R4AZc6PgjOb5-iKkyBaw_xTiRgGM5OJNHiXMY6TM");
            String weixinUrl = Play.configuration.getProperty("weixin.url");
            weixinUrl  = weixinUrl+ "payment/detail/bill/"+bill.id;
            wxMpTemplateMessage.setUrl(weixinUrl);
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("first", "您好！"+bill.user.realName!=null?bill.user.realName+",":""+currentMonth+"账单如下" ));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword1",bill.amount!=null? bill.amount+"元":""));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword2",DateUtil.dateToString(DateUtil.lastMonthOfFirstDay(new Date()),"yyyy-MM-dd")+" 到 "+DateUtil.dateToString(DateUtil.monthOfFirstDay(),"yyyy-MM-dd")));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword3", "物业管理费"));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword4", "无" ));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("remark", "请您在规定的时间内缴纳相关费用，如有疑问请及时联系我们，谢谢您的配合！"));


         /*   wxMpTemplateMessage.getData().add(new WxMpTemplateData("date",currentMonth));*/
//            wxMpTemplateMessage.getData().add(new WxMpTemplateData("billNums",billNums.toString()));
            try {
                wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
                bol = true;
            } catch (WxErrorException e) {
                Logger.info("weixinCode : %s 发送模板消息失败 . 错误原因 : %s", openId, e.getMessage());
            }
        }
        return bol;
    }

    /**
     * 客户绑定门禁卡消息推送
     * @param contractCardRelation
     * @param userOpenId
     * @return
     */
    public static Boolean bindAccessCard2(ContractCardRelation contractCardRelation, String userOpenId) {
        Boolean bol = false;
        String address="";
        if (contractCardRelation != null && contractCardRelation.accessCard != null) {
            String openId = userOpenId;
            if(StringUtils.isBlank(openId)) {
                bol = false;
                return bol;
            }
            if(contractCardRelation.contract!=null){
               List<ContractRoom>  contractRoomList=ContractRoom.findByContract(contractCardRelation.contract);
                if(contractRoomList!=null){
                    address= contractRoomList.get(0).room.building.campus.address;
                }

            }else {
                return bol;
            }
            System.out.println("bindAccessCard2,Work In"+openId);
            WxMpService wxMpService = getWxMpService(getWxMpConfigStorage());
            WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
            wxMpTemplateMessage.setToUser(openId);
            wxMpTemplateMessage.setTemplateId("-CuiMryKVEBbRBtWtX5XwOnotsxxFe6ph8MlrYXOV5U");
            String weixinUrl = Play.configuration.getProperty("weixin.url");
//            weixinUrl  = weixinUrl+ "payment/detail/bill/"+bill.id;
            wxMpTemplateMessage.setUrl(weixinUrl);
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("first", "业主您好！恭喜您已经入住成功！您的信息如下：" ));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("name",contractCardRelation.name!=null? contractCardRelation.name:""));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("tel",contractCardRelation.phone!=null? contractCardRelation.phone:""  ));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("address", address));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("remark", "欢迎您的入住，祝您生活愉快！"));
           /* wxMpTemplateMessage.getData().add(new WxMpTemplateData("cardNo",contractCardRelation.accessCard.code));*/
            try {
                wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
                bol = true;
            } catch (WxErrorException e) {
                Logger.info("weixinCode : %s 发送模板消息失败 . 错误原因 : %s", openId, e.getMessage());
            }
        }
        return bol;
    }

    /**
     * 每月8日定时代扣账单消息推送给客户
     * @param bill
     * @return
     */
    public static Boolean sendMsgToCustomForPayBills(Bill bill) {
        Boolean bol = false;
        if (bill != null && bill.user != null) {
            String openId = bill.user.openId;
            if(StringUtils.isBlank(openId)) {
                bol = false;
                return bol;
            }
            System.out.println("sendMsgToCustomForPayBills,Work In"+openId);
            String currentMonth = DateUtil.dateToString(DateUtil.lastMonthOfFirstDay(new Date()),"yyyy年MM月");
            WxMpService wxMpService = getWxMpService(getWxMpConfigStorage());
            WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
            wxMpTemplateMessage.setToUser(openId);
            wxMpTemplateMessage.setTemplateId("N9P-_e4v_AUdJ2zqWOus4-ynudAvYPzvW4fkKbgik_E");
            String weixinUrl = Play.configuration.getProperty("weixin.url");
            weixinUrl  = weixinUrl+ "payment/detail/bill/"+bill.id;
            wxMpTemplateMessage.setUrl(weixinUrl);

            wxMpTemplateMessage.getData().add(new WxMpTemplateData("first", "您好！您"+currentMonth+"的物业费已经代扣成功!" ));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword1","物业管理费"));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword2",bill.amount!=null? bill.amount+"元":""));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword3",DateUtil.dateToString(new Date(),"yyyy年MM月dd日 HH:mm")));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("remark", "感谢您的合作，如有疑问请联系我们!"));

            /*wxMpTemplateMessage.getData().add(new WxMpTemplateData("date",currentMonth));*/
            try {
                wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
                bol = true;
            } catch (WxErrorException e) {
                Logger.info("weixinCode : %s 发送模板消息失败 . 错误原因 : %s", openId, e.getMessage());
            }
        }
        return bol;
    }

    /**
     * 实时与客户沟通消息
     * @param user
     * @param msg
     * @return
     */
    public static Boolean sendMsgToCustomForConmunication(User user, String campId,String msg) {
        Boolean bol = false;
        Campus campus=null;
        if (user != null && StringUtils.isNotBlank(msg)) {
            String openId = user.openId;
            if(StringUtils.isBlank(openId)) {
                bol = false;
                return bol;
            }
            if(campId!=null){
                 campus=Campus.findByIdAndUnDeleted(campId);
            }else {
                return bol;
            }
            System.out.println("sendMsgToCustomForConmunication,Work In"+openId);
            WxMpService wxMpService = getWxMpService(getWxMpConfigStorage());
            WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
            wxMpTemplateMessage.setToUser(openId);
            wxMpTemplateMessage.setTemplateId("bBJQdCyqPtF34iV7qYoN8QBlqKs1NwStORNQJL1pAZ0");
            String weixinUrl = Play.configuration.getProperty("weixin.url");
//            weixinUrl  = weixinUrl+ "payment/detail/bill/"+bill.id;
            wxMpTemplateMessage.setUrl(weixinUrl);

            wxMpTemplateMessage.getData().add(new WxMpTemplateData("first", "业主您好，您的服务有了新的反馈！" ));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword1","报修反馈"));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword2",campus.address!=null? campus.address:""));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword3",DateUtil.dateToString(new Date(),"yyyy年MM月dd日 HH:mm")));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("keyword4",msg));
            wxMpTemplateMessage.getData().add(new WxMpTemplateData("remark", "谢谢您的合作！"));

         /*   wxMpTemplateMessage.getData().add(new WxMpTemplateData("msg",msg));*/
            try {
                wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
                bol = true;
            } catch (WxErrorException e) {
                Logger.info("weixinCode : %s 发送模板消息失败 . 错误原因 : %s", openId, e.getMessage());
            }
        }
        return bol;
    }
}
